package cn.dawn.webcollector.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * <p>解析properties文件</p>
 * <p>通过反射实现properties到java类文件的映射，目前支持类型:boolean,byte,short,int,float,double,long,string， java bean字段名必须与properties配置key一致，且必须为public</p>
 * @Copyright:Copyright (c) 2015
 * @Author:wangxiao
 * @Version:1.0
 * @Time:2015年10月10日
 */
public class ConfigParser {
	/**
	 * 从类路径加载配置并映射到类
	 * @param file
	 * @param clas
	 * @throws IllegalStateException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws IOException
	 */
	public static void parseFromClassPath(String file, Class<?> clas) throws IllegalStateException, IllegalArgumentException, IllegalAccessException, IOException {
		Properties prop = loadFromClassPath(file);
		assignment(clas, prop);
	}

	/**
	 * 从类路径加载配置
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private static Properties loadFromClassPath(String file) throws IOException {
		Properties prop = new Properties();
		InputStream inStream = ConfigParser.class.getClassLoader().getResourceAsStream(file);
		prop.load(inStream);
		return prop;
	}

	/**
	 * 给字段赋值
	 * @param obj
	 * @param prop
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	private static void assignment(Class<?> obj, Properties prop) throws IllegalArgumentException, IllegalAccessException {
		Field[] allFields = obj.getFields();
		for (Field field : allFields) {
			Class<?> type = field.getType();
			String fieldName = field.getName();
			String value = prop.getProperty(fieldName);
			if (type == boolean.class) {
				field.setBoolean(obj, Boolean.parseBoolean(value));
			} else if (type == byte.class) {
				field.setByte(obj, Byte.parseByte(value));
			} else if (type == short.class) {
				field.setShort(obj, Short.parseShort(value));
			} else if (type == int.class) {
				field.setInt(obj, Integer.parseInt(value));
			} else if (type == float.class) {
				field.setFloat(obj, Float.parseFloat(value));
			} else if (type == double.class) {
				field.setDouble(obj, Double.parseDouble(value));
			} else if (type == long.class) {
				field.setLong(obj, Long.parseLong(value));
			} else if (type == String.class) {
				field.set(obj, value);
			}
		}
	}
}